package scatter.identifier.rest.service.impl;

import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import scatter.common.rest.service.IAddServiceListener;
import scatter.common.rest.service.IUpdateServiceListener;
import scatter.identifier.pojo.form.IdentifierAddForm;
import scatter.identifier.pojo.form.IdentifierUpdateForm;
import scatter.identifier.pojo.po.Identifier;
import scatter.identifier.pojo.po.IdentifierPwd;
import scatter.identifier.rest.service.IIdentifierPwdService;

import java.time.LocalDateTime;

/**
 * Created by yangwei
 * Created at 2021/3/29 15:54
 */
@Component
public class IdentifierListenerImpl implements IAddServiceListener<Identifier, IdentifierAddForm>, IUpdateServiceListener<Identifier, IdentifierUpdateForm> {

    @Autowired
    @Lazy
    private IIdentifierPwdService identifierPwdService;

    @Override
    public void postAdd(IdentifierAddForm identifierAddForm, Identifier identifier) {
        if (!StrUtil.isEmpty(identifierAddForm.getPassword())) {
            savePassword(identifier, identifierAddForm.getPassword(),identifierAddForm.getPasswordComplexity());
        }
    }

    @Override
    public void postUpdate(IdentifierUpdateForm identifierUpdateForm, Identifier identifier) {
        if (!StrUtil.isEmpty(identifierUpdateForm.getPassword())) {
            savePassword(identifier, identifierUpdateForm.getPassword(),identifierUpdateForm.getPasswordComplexity());
        }
    }

    /**
     * 保存密码，不存在添加，存在更新
     * @param identifier
     * @param encodedPassword
     * @param passwordComplexity
     */
    private void savePassword(Identifier identifier, String encodedPassword,Integer passwordComplexity) {
        IdentifierPwd byIdentifierId = identifierPwdService.getByIdentifierId(identifier.getId());
        if (byIdentifierId != null) {
            byIdentifierId.setPwd(encodedPassword);
            byIdentifierId.setPwdModifiedAt(LocalDateTime.now());
            byIdentifierId.setComplexity(passwordComplexity);
            identifierPwdService.updateById(byIdentifierId);
        }else {
            byIdentifierId = new IdentifierPwd();

            byIdentifierId.setGroupFlag(identifier.getGroupFlag());
            byIdentifierId.setIsExpired(false);
            byIdentifierId.setIsNeedUpdate(false);
            byIdentifierId.setIdentifierId(identifier.getId());
            byIdentifierId.setPwd(encodedPassword);
            byIdentifierId.setPwdModifiedAt(LocalDateTime.now());
            byIdentifierId.setComplexity(passwordComplexity);

            identifierPwdService.save(byIdentifierId);
        }
    }
}
